package com.hsylient.mapper;

import com.hsylient.entity.Student;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Slf4j(topic = "springLog")
@Repository
public class StudentMapper {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Student> queryAll() {
        String querySql = "select * from test.student";
        List<Student> students = jdbcTemplate.query(querySql, new BeanPropertyRowMapper<>(Student.class));
        return students;
    }

    public Integer addStudent(Student student) {
        int affectedCount = jdbcTemplate.update("insert into test.student(name, age, birthday) " +
                "VALUES (?, ?, ?)", student.getName(), student.getAge(), student.getBirthday());
        return affectedCount;
    }

    public Integer deleteStudentById(@NonNull Integer id) {
        int affectedCount = jdbcTemplate.update("delete from test.student where id = ?", id);
        return affectedCount;
    }

    public Integer update(Student student) {
        int affectedCount = jdbcTemplate.update("update test.student set name = ? where id = ?", student.getName(), student.getId());
        return affectedCount;
    }
}
